//delManager.js
"use strict";

const fs = require("fs");
const path = require("path");

// 用法: node delManager.js <文件或文件夹名称>
const arg = process.argv[2];

function printUsage() {
	console.log("用法: node delManager.js <文件或文件夹名称>");
	console.log("说明: 仅在当前目录下操作 (相对当前工作目录)。");
}

if (!arg) {
	printUsage();
	process.exit(1);
}

// 防御: 禁止危险路径
const forbidden = new Set([".", "./", "..", "../", path.sep]);
if (forbidden.has(arg)) {
	console.error("错误: 不允许删除此路径。");
	process.exit(1);
}

// 解析到当前工作目录
const targetPath = path.resolve(process.cwd(), arg);

if (!fs.existsSync(targetPath)) {
	console.error(`错误: 路径不存在 -> ${targetPath}`);
	process.exit(1);
}

function deleteFileSync(filePath) {
	fs.unlinkSync(filePath);
}

function deleteDirRecursiveSync(dirPath) {
	// Node 14.14+ 可直接使用 rmSync 递归删除
	if (fs.rmSync) {
		fs.rmSync(dirPath, { recursive: true, force: true });
		return;
	}
	// 兼容实现
	const entries = fs.readdirSync(dirPath, { withFileTypes: true });
	for (const entry of entries) {
		const full = path.join(dirPath, entry.name);
		if (entry.isDirectory()) {
			deleteDirRecursiveSync(full);
		} else {
			fs.unlinkSync(full);
		}
	}
	fs.rmdirSync(dirPath);
}

try {
	const stat = fs.lstatSync(targetPath);
	if (stat.isDirectory()) {
		deleteDirRecursiveSync(targetPath);
		console.log(`已递归删除文件夹: ${targetPath}`);
	} else if (stat.isFile()) {
		deleteFileSync(targetPath);
		console.log(`已删除文件: ${targetPath}`);
	} else {
		console.error("错误: 仅支持删除普通文件或文件夹。");
		process.exit(1);
	}
} catch (err) {
	console.error("删除失败:", err.message);
	process.exit(1);
}